(ns memcached.core
  (:require [clj-xmemcached.core :as xm]
            [ring.util.codec :as rc]
            [clojure.string :as str]))

(defonce client (xm/memcached "localhost:11211" ))
(defmacro wxm
  [& body]
  `(xm/with-client client ~@body))

(wxm
 (xm/set (str "刘" (System/currentTimeMillis) (rand-int 10000)) 
         (str/join "_" (repeat 100   "家财")))
 ;; (xm/get "你好")
 ;; (xm/stats)
 )
(defn stats-items [& {:keys [timeout-ms] :or {timeout-ms (* 5 1000)}}]
  
  (wxm
   (->>
    (.getStatsByItem (xm/get-memcached-client) "items" timeout-ms)
    first
    val
    (filter #(str/ends-with? (.getKey %) "number"))
    (map #(let [item-num-ptn #"items:(\d+):number"
                [_ slab-id] (re-find item-num-ptn (.getKey %))]
            [slab-id (.getValue %)])))))

(defn list-keys [ & {:keys [limit slab-id timeout-ms]
                            :or {slab-id 1 limit 100 timeout-ms (* 5 1000)}}]
  (wxm
   (->>
    (.getStatsByItem (xm/get-memcached-client) (format "cachedump %s %s" slab-id limit) timeout-ms)
    first
    val
    (map #(let [k (.getKey %)]
            [k {:v (xm/get k)
                :expire }]))
    (into {}))))


(wxm
 (->> (.getStatsByItem (xm/get-memcached-client) "items" 10000)
      first
      val
      ;; (map first)
      seq
      ))
